// ignore_for_file: use_build_context_synchronously

import 'dart:async';
import 'dart:convert';

import 'package:client_flutter_door/model/door_model.dart';
import 'package:client_flutter_door/utils/info.dart';
import 'package:client_flutter_door/vars.dart';
import 'package:file_picker/_internal/file_picker_web.dart';
import 'package:file_picker/file_picker.dart';
import 'package:http/http.dart' as http;
import 'package:provider/provider.dart';

class Mongo {
  static Future<Map<String, String>> getUserczhs(String date) async {
    Map<String, String> temp = {};
    // print("开始获取测酒数目***");
    var request = http.Request('GET', Uri.parse('${Vars.mongoUrl}/data/$date'));
    http.StreamedResponse response = await request.send();
    if (response.statusCode == 200) {
      final result = await response.stream.bytesToString();
      Map<String, dynamic> data = jsonDecode(result);
      data.forEach((key, value) {
        temp[key] = '$value';
      });
    }
    if (temp.isEmpty) {
      await uploadUserczhs();
    }
    return temp;
  }

  static uploadUserczhs() async {
    FilePickerResult? result = await FilePickerWeb.platform.pickFiles(
      // FilePickerResult? result = await FilePicker.platform.pickFiles(
// type: FileType.custom,
// allowedExtensions: ['xlsm'],
      withReadStream: true,
    );
    if (result != null) {
// print(result.files.single.name);
// print(result.files.single.extension);
// print(result.files.single.size);
      PlatformFile objFile = result.files.single;
//---Create http package multipart request object
      final request = http.MultipartRequest(
        "POST",
        Uri.parse("${Vars.mongoUrl}/upfile"),
      );
// //-----add other fields if needed
// request.fields["id"] = "abc";

// //-----add selected file with request
      request.files.add(http.MultipartFile(
          "file", objFile.readStream!, objFile.size,
          filename: objFile.name));

// //-------Send request
      var response = await request.send();
      if (response.statusCode == 200) {
        String result = await response.stream.bytesToString();
        Map<String, dynamic> data = jsonDecode(result);
        if (data["file"]!=null) {
          Info.snackbarWithoutContext('上传成功');
          await Vars.navigatorKey.currentContext!
              .read<DoorModel>()
              .getUserczhs();
        }
      } else {
        Info.snackbarWithoutContext('上传出错');
      }
// //------Read response

// //-------Your response
    } else {
// User canceled the picker
      // Info.snackbarWithoutContext('取消上传');
    }
  }
}
